<template>
  <div>
    <router-view/>
    <el-container>
      <el-aside width="400px" style="display: flex; flex-direction: column;">
        <el-row style="margin-top: 20px">
          <div class="font" style="margin-bottom: 20px"><p>一些常见问题</p></div>
          <el-button style="margin-top: 3px" plain @click="askChat('我今天有点发烧')">我今天有点发烧</el-button>
          <el-button style="margin-top: 3px" type="primary" plain @click="askChat('我今天嗓子疼')">我今天嗓子疼
          </el-button>
          <br>
          <el-button style="margin-top: 3px" type="success" plain @click="askChat('有点头疼')">有点头疼</el-button>
          <el-button style="margin-top: 3px" type="info" plain @click="askChat('肚子不舒服')">肚子不舒服</el-button>
          <br>
          <el-button style="margin-top: 3px" type="warning" plain @click="askChat('胳膊疼')">胳膊疼</el-button>
          <el-button style="margin-top: 3px" type="danger" plain @click="askChat('头晕目眩的')">头晕目眩的
          </el-button>
          <el-button style="margin-top: 3px" plain @click="askChat('吃饭没有胃口')">吃饭没有胃口</el-button>
          <el-button style="margin-top: 3px" type="primary" plain @click="askChat('口干舌燥')">口干舌燥</el-button>
          <el-button style="margin-top: 3px" type="success" plain @click="askChat('眼睛干涩胀痛')">眼睛干涩胀痛
          </el-button>
          <el-button style="margin-top: 3px" type="info" plain @click="askChat('拉肚子')">拉肚子</el-button>
          <br>
          <el-button style="margin-top: 3px" type="warning" plain @click="askChat('上火')">上火</el-button>
          <el-button style="margin-top: 3px" type="success" plain @click="askChat('我的嘴里长了个包')">
            我的嘴里长了个包
          </el-button>
          <el-button style="margin-top: 3px" type="info" plain @click="askChat('我鼻子很不舒服')">我鼻子很不舒服
          </el-button>
          <br>
          <el-button style="margin-top: 3px" type="danger" plain @click="askChat('失眠了')">失眠了</el-button>
          <el-button style="margin-top: 3px" type="warning" plain @click="askChat('最近一直犯困')">最近一直犯困
          </el-button>
          <el-button style="margin-top: 3px" plain @click="askChat('经常打喷嚏')">经常打喷嚏</el-button>
          <el-button style="margin-top: 3px" type="info" plain @click="askChat('皮肤瘙痒或红肿')">皮肤瘙痒或红肿
          </el-button>
          <br>
          <el-button style="margin-top: 3px" type="danger" plain @click="askChat('背痛')">背痛</el-button>
          <el-button style="margin-top: 3px" type="warning" plain @click="askChat('肩膀或颈部疼痛')">
            肩膀或颈部疼痛
          </el-button>
          <el-button style="margin-top: 3px" plain @click="askChat('眼睛干涩疲劳')">眼睛干涩疲劳</el-button>
          <el-button style="margin-top: 3px" type="warning" plain @click="askChat('心悸')">心悸</el-button>
          <el-button style="margin-top: 3px" plain @click="askChat('咳嗽不止')">咳嗽不止</el-button>
          <el-button style="margin-top: 3px" type="info" plain @click="askChat('脱发增多')">脱发增多</el-button>
          <br>
          <el-button style="margin-top: 3px" type="warning" plain @click="askChat('体重变化明显')">体重变化明显
          </el-button>
          <el-button style="margin-top: 3px" plain @click="askChat('耳鸣')">耳鸣</el-button>
          <el-button style="margin-top: 3px" type="info" plain @click="askChat('经常性疲劳')">经常性疲劳</el-button>
          <br>
        </el-row>
        <el-divider></el-divider>
        <div style="flex-grow: 1;">
          <div style="flex-grow: 1;">语音转文字
            <div style="margin-top: 10px;margin-bottom: 10px;margin-right: 10px;margin-left: 10px">
              <el-input :readonly="true" id="word" v-model="word"></el-input>
            </div>
            <div>
              <el-button type="primary" @click="audioCHangeWord"><span v-if="isListening">语音识别中...</span><span
                  v-else>语音识别</span></el-button>
              <el-button type="success" icon="el-icon-check" @click="askChat(this.word)">提交信息
              </el-button>
            </div>
          </div>
        </div>

      </el-aside>

      <el-container>
        <el-header class="styled-header">
          <el-menu mode="horizontal" @select="handleSelect" router="router">
            <el-menu-item index="/drug">药品检索</el-menu-item>
            <el-menu-item index="/case">病例说明</el-menu-item>
            <el-menu-item index="/symptom">症状查询</el-menu-item>
            <el-menu-item index="/place">医院信息查找</el-menu-item>
            <el-button type="text">？使用说明</el-button>
          </el-menu>
        </el-header>

        <el-main
            style=" align-items: center; flex-direction: column; height: 580px; max-width: 100%;">
          <el-card shadow="hover" style="margin-right: 5px;width: 720px">
            <el-descriptions class="margin-top" :column="3">
              <el-descriptions-item label="AI推荐">
                <div>
                  {{messages}}
                </div>
              </el-descriptions-item>
            </el-descriptions>
            <el-button type="success" @click="speakTtsSpeech">语音播报</el-button>
          </el-card>
        </el-main>
      </el-container>
    </el-container>

  </div>
</template>
<script>
import request from "@/utils/request";
import Speech from 'speak-tts'

export default {
  name: "AudioToWord",
  data() {
    return {
      //主显示内容
      desc: '',
      speech: '',
      //使用说明
      centerDialogVisible: false,
      //语言转文字
      word: "",
      isListening: false, // 判断是否在语音监听中
      messages: "",
      currentIndex: 0
    };
  },
  methods: {
    navigateTo(route) {
      this.$router.push(route);
    },
    // 播报系统js
    //初始化播报系统
    speechInit() {
      this.speech = new Speech();
      this.speech.setLanguage("zh-CN");
      this.speech.init().then(() => {
      });
    },
    //为按钮添加了点击播报事件
    speakTtsSpeech() {
      this.speech.speak({text: this.desc}).then(() => {
      });
    },
    //语音转文字功能
    audioCHangeWord() {
      var that = this;
      that.word = "";
      // 创建SpeechRecognition对象
      // eslint-disable-next-line no-undef
      var recognition = new webkitSpeechRecognition();
      if (!recognition) {
        // eslint-disable-next-line no-undef
        recognition = new SpeechRecognition();
      }
      // 设置语言
      recognition.lang = 'zh-CN';
      // 开始语音识别
      recognition.start();
      that.isListening = true;
      // 监听识别结果
      recognition.onresult = function (event) {
        var result = event.results[0][0].transcript;
        that.word = result;
      };

      // 监听错误事件
      recognition.onerror = function (event) {
        that.isListening = false;
        that.$message("监听语音失败:" + event.error);
        console.error(event.error);
      };
      // 监听结束事件（包括识别成功、识别错误和用户停止）
      recognition.onend = function () {
        that.isListening = false;
        console.log("语音识别停止");
      };

    },

    async askChat(value) {
      var _this = this
      _this.messages=""
      const response = await fetch('http://localhost:8088/ai/qianfan', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({str: value})
      });
      if (response.ok) {
        const reader = response.body.getReader();
        const stream = new ReadableStream({
          async start(controller) {
            function fetchData() {
              reader.read().then(({done, value}) => {
                if (done) {
                  controller.close();
                  return;
                }
                const chunkText = new TextDecoder().decode(value);
                async function processChunkText(chunkText) {
                  try {
                    const dataArray = JSON.parse(chunkText);
                    for (const data of dataArray) {
                      if (data.end === true) {
                        return;
                      }
                      if (data.result) {
                        const text = data.result;
                        // 假设 _this 是当前上下文的引用，确保它在函数外部已经定义
                        _this.messages += text;
                        // 休眠一秒钟
                        await new Promise(resolve => setTimeout(resolve, 1000));
                      }
                    }
                  } catch (error) {
                    // 处理 JSON.parse 可能出现的错误
                    console.error('Error parsing JSON:', error);
                  }
                }
                processChunkText(chunkText)
                fetchData();
              });
            }
            fetchData();
          }
        });
        console.log(_this.messages)
        await new Response(stream).text();
      } else {
        this.$message.error('发生错误')
      }
    }

  },
  mounted() {
    this.speechInit();
    //通过 ref 获取到的 video 元素赋值给组件实例的 videoElement 属性
    this.videoElement = this.$refs.video;
    //通过 ref 获取到的 canvas 元素赋值给组件实例的 canvasElement 属性
    this.canvasElement = this.$refs.canvas;
  }
}
</script>

<style>
.font {
  font-family: 'Roboto', sans-serif;
  font-size: 16px;
  font-weight: 400;
  color: #333;
}

.styled-header {
  font-size: 24px; /* 设置字体大小 */
  font-weight: bold; /* 设置字体加粗 */
  color: #333; /* 设置字体颜色 */
  text-align: center; /* 设置文本居中 */
  padding: 20px 0; /* 设置上下内边距 */
  border-bottom: 2px solid #ccc; /* 添加底部边框 */
  background-color: #f0f0f0; /* 设置背景颜色 */
}

.el-header {

  background-color: #cedaf8;
  text-align: center;
}

.el-aside {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
}

.el-main {
  background-color: #f0f0f0;
  color: #333;
  text-align: center;

}

.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 968px;
  margin-top: 10px;
}

.box-card1 {
  width: 968px;
  margin-top: 10px;
}
</style>